import configparser
import os

from common.utils import to_abs_path


class Config:
    def __init__(self, config_file=to_abs_path('config.ini')):
        self.config = configparser.ConfigParser()
        self.config.read(config_file)

        self.APP_NAME = self.config.get('app', 'name')

        # MySQL 配置
        self.MYSQL_HOST = self.config.get('mysql', 'host')
        self.MYSQL_USER = self.config.get('mysql', 'user')
        self.MYSQL_PASSWORD = self.config.get('mysql', 'password')
        self.MYSQL_DATABASE = self.config.get('mysql', 'database')

        # Redis 配置
        self.REDIS_HOST = self.config.get('redis', 'host')
        self.REDIS_PORT = self.config.getint('redis', 'port')
        self.REDIS_PASSWORD = self.config.get('redis', 'password', fallback='')
        self.REDIS_DB = self.config.getint('redis', 'db')

        self.LOG_FILE = self.config.get('logger', 'log_file')

        # Milvus 配置
        self.MILVUS_HOST = self.config.get('milvus', 'host', fallback='localhost')
        self.MILVUS_PORT = self.config.get('milvus', 'port', fallback='19530')
        self.MILVUS_DATABASE_NAME = self.config.get('milvus', 'database_name', fallback='edu-rag')
        self.MILVUS_COLLECTION_NAME = self.config.get('milvus', 'collection_name', fallback='edu-rag')

        # LLM 配置
        self.LLM_MODEL = self.config.get('llm', 'model', fallback='qwen-plus')
        self.DASHSCOPE_API_KEY = self.config.get('llm', 'dashscope_api_key', fallback=os.getenv('DASHSCOPE_API_KEY'))
        self.DASHSCOPE_BASE_URL = self.config.get('llm', 'dashscope_base_url',
                                                  fallback='https://dashscope.aliyuncs.com/compatible-mode/v1')

        # 检索参数
        # 父块大小
        self.PARENT_CHUNK_SIZE = self.config.getint('retrieval', 'parent_chunk_size', fallback=1200)
        # 子块大小
        self.CHILD_CHUNK_SIZE = self.config.getint('retrieval', 'child_chunk_size', fallback=300)
        # 块重叠大小
        self.CHUNK_OVERLAP = self.config.getint('retrieval', 'chunk_overlap', fallback=50)
        # 检索返回数量
        self.RETRIEVAL_K = self.config.getint('retrieval', 'retrieval_k', fallback=5)
        # 最终候选数量
        self.CANDIDATE_M = self.config.getint('retrieval', 'candidate_m', fallback=2)

        # 应用配置
        # 有效来源列表
        self.VALID_SOURCES = eval(
            self.config.get('app', 'valid_sources', fallback='["ai", "java", "test", "ops", "bigdata"]'))
        # 客服电话
        self.CUSTOMER_SERVICE_PHONE = self.config.get('app', 'customer_service_phone', fallback='12345678')


config = Config()
